package common

import (
	"context"
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/common/simplecopier"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/constants"
	pb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/common"
	"git.myscrm.cn/golang/stark/v4"
)

type FormRepository struct {
}

func NewFormRepository() FormRepositoryIface {
	return &FormRepository{}
}

func (f *FormRepository) GetFormTemplateConfig(ctx context.Context, templateId string) ([]map[string]interface{}, error) {
	request := &pb.GetFormTemplateConfigRequest{
		TemplateId: templateId,
	}

	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()
	client := pb.NewFormServiceClient(conn)
	resp, err := client.GetFormTemplateConfig(ctx, request)
	if err != nil {
		return nil, err
	}
	if resp == nil {
		return nil, nil
	}

	result, err := simplecopier.StructToMapByJsonTag(resp)
	if err != nil {
		stark.Logger.Error(ctx, "获取模板配置repository 结果json解析失败", err)
		return nil, err
	}

	if _, ok := result["data"]; ok {
		tempateList := make([]map[string]interface{}, len(result["data"].([]interface{})))
		for i, item := range result["data"].([]interface{}) {
			if tempMap, ok := item.(map[string]interface{}); ok {
				tempateList[i] = tempMap
			} else {
				stark.Logger.Errorf(ctx, "模板配置解析失败，value:%v", result)
			}
		}
		return tempateList, nil
	} else {
		return nil, nil
	}
}

func (f *FormRepository) GetFormDataRule(ctx context.Context, key string) ([]map[string]interface{}, error) {
	request := &pb.GetFormDataRuleRequest{
		RuleIds: key,
	}

	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewFormServiceClient(conn)
	resp, err := client.GetFormDataRule(ctx, request)
	if err != nil {
		return nil, err
	}
	if resp == nil {
		return nil, nil
	}

	result, err := simplecopier.StructToMapByJsonTag(resp)
	if err != nil {
		return nil, err
	}

	if _, ok := result["data"]; ok {
		ruleList := make([]map[string]interface{}, len(result["data"].([]interface{})))
		for i, item := range result["data"].([]interface{}) {
			if tempMap, ok := item.(map[string]interface{}); ok {
				ruleList[i] = tempMap
			} else {
				stark.Logger.Errorf(ctx, "模板数据规则解析失败，value:%v", result)
			}
		}
		return ruleList, nil
	} else {
		return nil, nil
	}
}
